package com.example.personblog.service;

import com.example.personblog.common.ResultEnum;
import com.example.personblog.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import com.example.personblog.repository.PostRepository;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class LikeService {
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    @Autowired
    private PostRepository postRepository;
    
    private static final String LIKE_KEY = "post:like:";
    private static final String USER_LIKE_KEY = "user:like:";
    
    /**
     * 点赞/取消点赞
     */
    @Transactional
    public boolean like(Long postId, Long userId) {
        try {
            String postLikeKey = LIKE_KEY + postId;
            String userLikeKey = USER_LIKE_KEY + userId;
            
            Boolean isMember = redisTemplate.opsForSet().isMember(postLikeKey, userId.toString());
            if (Boolean.TRUE.equals(isMember)) {
                // 取消点赞
                redisTemplate.opsForSet().remove(postLikeKey, userId.toString());
                redisTemplate.opsForSet().remove(userLikeKey, postId.toString());
                postRepository.decrementLikes(postId);
                return false;
            } else {
                // 添加点赞
                redisTemplate.opsForSet().add(postLikeKey, userId.toString());
                redisTemplate.opsForSet().add(userLikeKey, postId.toString());
                postRepository.incrementLikes(postId);
                return true;
            }
        } catch (Exception e) {
            log.error("点赞操作失败", e);
            throw new BusinessException(ResultEnum.SYSTEM_ERROR);
        }
    }
    
    /**
     * 获取点赞数量
     */
    public Long getLikeCount(Long postId) {
        return redisTemplate.opsForSet().size(LIKE_KEY + postId);
    }
    
    /**
     * 检查用户是否点赞
     */
    public boolean hasLiked(Long postId, Long userId) {
        return Boolean.TRUE.equals(redisTemplate.opsForSet().isMember(LIKE_KEY + postId, userId.toString()));
    }
} 